package org.autumn.lock;

import java.util.ArrayList;

/**
 * ThreadSafeSub 如果将list暴露给多线程使用,将会出现并发问题
 */
public class Expose {
    public static void main(String[] args) {

        int threadNum = 2;
        int loopNum = 200;
        ThreadSafeSub threadSafe = new ThreadSafeSub();
        for (int i = 0; i < threadNum; i++) {
            new Thread(() -> {
                for (int j = 0; j < loopNum; j++) {
                    threadSafe.m1();
                }
            }, "t" + i).start();
        }
    }
}

class ThreadSafe{

    public void m1(){
        ArrayList<Object> list = new ArrayList<>();
        m2(list);
        m3(list);
    }

    public void m2(ArrayList<Object> list){
        list.add(1);
    }

    public void m3(ArrayList<Object> list){
        list.remove(0);
    }
}

class ThreadSafeSub extends ThreadSafe{
    @Override
    public void m3(ArrayList<Object> list) {
        new Thread(() -> list.remove(1), "sub").start();
    }
}
